<script setup lang="ts">
import { ElMessage, FormInstance } from 'element-plus';
import { reactive, ref } from 'vue';
import { invoke } from '@tauri-apps/api/core';
import { useRouter } from 'vue-router';
import { InternalRuleItem, Value } from "async-validator";
import { load_rtdata_subscriber_service_dxc, load_user_dxc, load_xcom_service_dxc } from '@/dxc';
import * as userService from "@/assets/api/userservice_0_0_1";
import * as xcomService from "@/assets/api/xcomservice_0_0_1";


const router = useRouter();
const loginFormRef = ref<FormInstance>();

const data = reactive<{
  showAdd: boolean // 用于判断当前是登录页，还是添加用户页
}>({
  showAdd: false
});

const loginFormModel = reactive<{
  account: string, // 账户名
  password: string  // 密码
  repassword: string  // 重复密码
  rememberPassword: boolean // 是否记住密码
}>({
  account: "",
  password: "",
  repassword: "",
  rememberPassword: false
});

// 登录函数
const onLogin = async () => {
  // 对输入参数进行验证
  const validate = await loginFormRef.value.validate();
  if (!validate) {
    return;
  }
  // 登录
  const res = await userService.Login({
    username: loginFormModel.account,
    password: loginFormModel.password,
    remember: loginFormModel.rememberPassword
  });
  if (res.err_code !== 0) {
    ElMessage.error(res.err_msg);
    return;
  }
  // 登录成功，跳转到页面
  router.push("/quotes");
};

// 添加账号
const onAddAccount = async () => {
  // 对输入参数进行验证
  const validate = await loginFormRef.value.validate();
  if (!validate) {
    return;
  }
  // 调用接口添加账号
  const res = await userService.AddUser({
    username: loginFormModel.account,
    password: loginFormModel.password,
    remember: false,
  });
  if (res.err_code !== 0) {
    ElMessage.error(res.err_msg);
    return;
  }
  // 登录成功
  data.showAdd = false;
};


// 验证两次密码是否一致
const rePassValidator = (rule: InternalRuleItem, value: Value, callback: (error?: string | Error) => void) => {
  if (value === loginFormModel.password) {
    callback();
  } else {
    callback(new Error("两次输入密码不同"));
  }
};

// 加载上一次登录时记住的密码
const loadRemomberPassword = async () => {
  const res = await userService.GetRememberAccount();
  console.log(res);
  if (res.err_code !== 0 || !res.data) {
    return;
  }
  if (res.data.username) {
    loginFormModel.rememberPassword = true;
    loginFormModel.account = res.data.username;
    loginFormModel.password = res.data.password;
  }
};

const connectToRealtimeNode = async()=>{
  const res = await xcomService.BuildChannel({
    node_url: "dxm://127.0.0.1:8090",
    is_keep: true
  });

  console.log(res);
};

// 初始化 xPort
const onInitxPort = async () => {
  const is_init = await invoke("is_init_xport");
  if (!is_init) {
    await invoke("boot_xport");
    await load_xcom_service_dxc();
    console.log("加载用户组件。。。")
    await load_user_dxc();
    console.log("加载数据组件。。。")
    await load_rtdata_subscriber_service_dxc();
    //
    await connectToRealtimeNode();
  }
};
// 进入页面，开始初始化
const onInit = async () => {
  await onInitxPort();
  await loadRemomberPassword();
};

onInit();
</script>

<template>
  <el-form ref="loginFormRef" :model="loginFormModel" label-position="top">
    <el-form-item prop="account" label="" :rules="[
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ]">
      <el-input v-model="loginFormModel.account" placeholder="请输入用户名/手机号" />
    </el-form-item>

    <el-form-item prop="password" label="" :rules="[
    { required: true, message: '密码不能为空', trigger: 'blur' }
  ]">
      <el-input type="password" v-model="loginFormModel.password" placeholder="请输入密码" />
    </el-form-item>


    <div v-if="!data.showAdd" class="horzontal-center-layout ">
      <el-checkbox label="记住密码" v-model="loginFormModel.rememberPassword" />
    </div>

    <el-form-item v-else prop="repassword" label="" :rules="[{ required: true, message: '密码不能为空', trigger: 'blur' },
  { required: true, validator: rePassValidator, message: '确认密码（8至16位数英文数字组合）且与密码相同', trigger: 'blur' }]">
      <el-input type="password" v-model="loginFormModel.repassword" placeholder="再次输入密码" />
    </el-form-item>


    <div v-if="!data.showAdd" class="horzontal-center-layout account-login-btn-bar ">
      <el-button class="login-btn" @click="onLogin">登录</el-button>
    </div>

    <div v-else class="horzontal-center-layout account-login-btn-bar ">
      <el-button class="login-btn" @click="onAddAccount">添加账号</el-button>
    </div>

    <div class="bottom-bar horzontal-center-layout flex-center">
      <div v-if="!data.showAdd" class="add-account" @click="data.showAdd = true"> 添加账号</div>
      <div v-else class="add-account" @click="data.showAdd = false"> 账号登录</div>
      <div class="spliter">|</div>
      <div>更多选项</div>
    </div>
  </el-form>

</template>


<style scoped lang="scss">
.account-form {
  margin-top: 30px;
  padding: 0 30px;
  display: flex;
  flex-direction: column; /* 改为竖直排列 */
  justify-content: center;
  align-items: center;
  max-width: 500px; /* 控制登录框的最大宽度 */
  margin-left: auto;
  margin-right: auto; /* 使容器水平居中 */
  background-color: white; /* 背景色可以根据需要调整 */
  border-radius: 10px; /* 圆角效果 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding-top: 50px; /* 可以调整顶部间距，防止内容紧贴顶部 */

  /* 标签样式优化 */
  :deep(.el-form-item__label) {
    font-weight: bold;
    font-size: 16px;
    color: #333;
    margin-bottom: 8px; /* 适当调整标签与输入框的间距 */
    letter-spacing: 0.5px;
  }

  /* 输入框样式优化 */
  :deep(.el-input__wrapper) {
    padding: 8px 14px;
    border: 1px solid #ccc;
    border-radius: 8px;
    outline: none;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    background-color: #f9f9f9;
    transition: all 0.3s ease;
    
    &:hover {
      border-color: #250dff;
    }
    
    &:focus-within {
      border-color: #2F49D0;
      box-shadow: 0 2px 12px rgba(47, 73, 208, 0.3);
    }
  }

  /* 图标和表单顶部的间距 */
  > img {
    width: 60px;
    height: 60px;
    display: block;
    margin-bottom: 50px;
    transition: all 0.3s ease;
  }

  /* 忘记密码按钮 */
  .forget-btn {
    font-size: 14px;
    font-weight: 500;
    color: #2F49D0;
    transition: color 0.3s ease;
    
    &:hover {
      color: #1F3BA1;
    }
  }

  /* 登录按钮区域 */
  .account-login-btn-bar {
    margin-top: 30px;
    width: 100%;
  }

  /* 按钮样式 */
  .login-btn,
  .register-btn {
    width: 100%;
    height: 40px;
    border-radius: 8px;
    font-size: 16px;
    font-weight: bold;
    display: inline-block;
    border: none;
    outline: none;
    cursor: pointer;
    transition: all 0.3s ease;
    text-transform: uppercase;
  }

  .login-btn {
    color: white;
    background: linear-gradient(90deg, #ff87c9, #d94ca8);
    box-shadow: 0 4px 8px rgba(0, 153, 255, 0.3);
    
    &:hover {
      background: linear-gradient(90deg, #ff0101, #380202);
      box-shadow: 0 4px 12px rgba(0, 153, 255, 0.5);
    }
  }

  .register-btn {
    color: #2F49D0;
    border: 2px solid #0333f1;
    background: transparent;
    
    &:hover {
      background-color: #2F49D0;
      color: white;
    }
  }

  /* 底部栏样式 */
  .bottom-bar {
    margin-top: 30px;
    color: #000000;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    
    .spliter {
      margin: 0 10px;
      color: #ff0707;
    }
    
    .add-account {
      cursor: pointer;
      font-weight: 500;
      color: #000000;
      transition: color 0.3s ease;
      
      &:hover {
        color: #eb0c0c;
      }
    }
  }

  /* 响应式优化 */
  @media (max-width: 768px) {
    padding: 0 20px;

    > img {
      width: 50px;
      height: 50px;
      margin-bottom: 40px;
    }

    .login-btn,
    .register-btn {
      height: 35px;
      font-size: 14px;
    }

    .bottom-bar {
      margin-top: 20px;
    }
  }
}


</style>